/*
 * Copyright 2009-2010 Original Author(s)
 * 
 * This file is part of Kommando
 * 
 * Kommando is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * Kommando is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with Kommando.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.kommando.core.internal;

import java.awt.KeyEventDispatcher;
import java.awt.KeyboardFocusManager;

import javax.swing.SwingUtilities;
import javax.swing.UIManager;

import org.kommando.core.DefaultKommando;
import org.kommando.core.Kommando;
import org.kommando.core.action.Action;
import org.kommando.core.action.ActionRepository;
import org.kommando.core.action.DefaultActionRepository;
import org.kommando.core.catalog.Catalog;
import org.kommando.core.catalog.DefaultCatalog;
import org.kommando.core.catalog.ObjectSource;
import org.kommando.skin.DefaultSkinManager;
import org.kommando.skin.Skin;
import org.kommando.skin.SkinManager;
import org.kommando.util.osgi.ServiceCollectionUtils;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.util.tracker.ServiceTracker;

import ca.odell.glazedlists.EventList;
import ca.odell.glazedlists.event.ListEvent;
import ca.odell.glazedlists.event.ListEventListener;

import com.jgoodies.looks.windows.WindowsLookAndFeel;

public class KommandoCoreActivator implements BundleActivator {

    private ServiceTracker keyEventDispatcherTracker;

    public void start(final BundleContext context) throws Exception {
        UIManager.put("ClassLoader", getClass().getClassLoader());
        UIManager.setLookAndFeel(new WindowsLookAndFeel());

        final ActionRepository actionRepository = new DefaultActionRepository(ServiceCollectionUtils.getServiceList(context, Action.class));
        final Catalog catalog = new DefaultCatalog(ServiceCollectionUtils.getServiceList(context, ObjectSource.class));

        keyEventDispatcherTracker = new ServiceTracker(context, KeyEventDispatcher.class.getName(), null) {
            @Override
            public Object addingService(ServiceReference reference) {
                KeyEventDispatcher service = (KeyEventDispatcher) super.addingService(reference);

                KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(service);

                return service;
            }

            @Override
            public void removedService(ServiceReference reference, Object service) {
                KeyboardFocusManager.getCurrentKeyboardFocusManager().removeKeyEventDispatcher((KeyEventDispatcher) service);

                super.removedService(reference, service);
            }
        };
        keyEventDispatcherTracker.open();

        SwingUtilities.invokeAndWait(new Runnable() {
            @Override
            public void run() {
                Kommando kommando = new DefaultKommando(catalog, actionRepository);
                context.registerService(Kommando.class.getName(), kommando, null);

                EventList<Skin> skins = ServiceCollectionUtils.getServiceList(context, Skin.class);
                final SkinManager skinManager = new DefaultSkinManager(kommando, skins);
                if (!skins.isEmpty()) {
                    skinManager.setCurrent(skins.get(0));
                }

                skins.addListEventListener(new ListEventListener<Skin>() {
                    @Override
                    public void listChanged(ListEvent<Skin> e) {
                        if (skinManager.getCurrent() == null) {
                            SwingUtilities.invokeLater(new Runnable() {
                                @Override
                                public void run() {
                                    skinManager.setCurrent(skinManager.getSkins().get(0));
                                }
                            });
                        }

                    }
                });
            }
        });

        context.registerService(Catalog.class.getName(), catalog, null);

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                catalog.index();
            }
        }, "Catalog Indexer").start();
    }

    public void stop(BundleContext context) throws Exception {
        keyEventDispatcherTracker.close();
    }
}
